package com.example.game.app.config;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import com.example.game.app.util.JwtTokenUtil;

@Component
public class JwtAuthenticationInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, 
                           HttpServletResponse response, 
                           Object handler) throws Exception {
        String authHeader = request.getHeader("Authorization");
        
        // 1. 检查Authorization头是否存在
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            response.sendError(HttpStatus.UNAUTHORIZED.value(), "无效的授权头");
            return false;
        }
        
        // 2. 提取Token部分
        String token = authHeader.substring(7);
        
        try {
            if (!jwtTokenUtil.validateToken(token)) {
                response.sendError(HttpStatus.UNAUTHORIZED.value(), "无效的Token");
                return false;
            }
            return true;
        } catch (Exception e) {
            response.sendError(HttpStatus.UNAUTHORIZED.value(), "Token验证失败: " + e.getMessage());
            return false;
        }
    }
}